package com.siruier.boss.ui.helper

import android.app.Activity
import android.content.Context
import android.graphics.Bitmap
import android.graphics.Paint
import android.os.Build
import android.os.Environment
import android.widget.ImageView
import androidx.lifecycle.LifecycleOwner
import com.bumptech.glide.Glide
import com.siruier.boss.BuildConfig
import com.siruier.boss.R
import com.siruier.boss.api.MALL_API_SERVICE
import com.siruier.boss.api.core.FirmException
import com.siruier.boss.api.core.launchUI
import com.siruier.boss.api.core.toData
import com.siruier.boss.api.mallApi
import com.siruier.boss.common.MINI_PROGRAM_APP_ID
import com.siruier.boss.common.MINI_PROGRAM_USER_NAME
import com.siruier.boss.common.handleLoginName
import com.siruier.boss.databinding.ViewGoodsShareWeixinCircleBinding
import com.siruier.boss.databinding.ViewGoodsShareWxBinding
import com.siruier.boss.databinding.ViewOrderTransferBinding
import com.siruier.boss.ui.api.ApiObserver
import com.siruier.boss.ui.base.BaseActivity
import com.siruier.boss.ui.cache.UserCache
import com.siruier.boss.ui.dialog.showAlertInputDialog
import com.siruier.boss.ui.ext.*
import com.siruier.boss.ui.utils.AlbumUtils
import com.siruier.boss.ui.utils.Logger
import com.tencent.mm.opensdk.modelmsg.SendMessageToWX
import com.tencent.mm.opensdk.modelmsg.WXMediaMessage
import com.tencent.mm.opensdk.modelmsg.WXMiniProgramObject
import com.tencent.mm.opensdk.openapi.WXAPIFactory
import com.umeng.socialize.Config
import com.umeng.socialize.ShareAction
import com.umeng.socialize.bean.SHARE_MEDIA
import com.umeng.socialize.media.UMImage
import com.umeng.socialize.media.UMMin
import com.yanzhenjie.permission.runtime.Permission
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.suspendCancellableCoroutine
import kotlinx.coroutines.withContext
import top.zibin.luban.Luban
import kotlin.coroutines.resume
import kotlin.coroutines.resumeWithException


object ShareHelper {

    fun LifecycleOwner.shareMiniProgram(context: Context, path: String, title: String, url: String) {
        launchUI({ suspendShareMiniProgram(context, path, title, url) }, ApiObserver())
    }

    private suspend fun suspendShareMiniProgram(context: Context, path: String, title: String, url: String) {
        val thumb = withContext(Dispatchers.IO) {
            val file = Glide.with(context)
                .asFile()
                .load(url)
                .submit()
                .get()
            Luban.with(context).load(file).get()[0].readBytes()
        }
        suspendShareMiniProgram(context, path, title, thumb)
    }

    private fun suspendShareMiniProgram(context: Context?, path: String, title: String, bitmap: Bitmap) {
        val umMin = UMMin("http://www.qq.com")
        umMin.setThumb(UMImage(context, bitmap))
        if (BuildConfig.DEBUG) {
            Config.setMiniPreView()
        }
        umMin.userName = MINI_PROGRAM_USER_NAME
        umMin.path = path
        umMin.title = title
        // 小程序消息desc
        umMin.description = title
        // 小程序消息封面图片，小于128k
        umMin.setThumb(UMImage(context, bitmap))
        ShareAction(context as Activity)
            .setPlatform(SHARE_MEDIA.WEIXIN)
            .withMedia(umMin)
            .share()
    }

    private fun suspendShareMiniProgram(context: Context, path: String, title: String, thumb: ByteArray) {
        val appId = MINI_PROGRAM_APP_ID
        val api = WXAPIFactory.createWXAPI(context, appId)
        val miniProgramObj = WXMiniProgramObject()
        // 兼容低版本的网页链接
        miniProgramObj.webpageUrl = "http://www.qq.com"
        // 正式版:0，测试版:1，体验版:2

        miniProgramObj.miniprogramType = if (BuildConfig.DEBUG) {
            WXMiniProgramObject.MINIPROGRAM_TYPE_PREVIEW
        } else {
            WXMiniProgramObject.MINIPTOGRAM_TYPE_RELEASE
        }
        // 小程序原始id
        miniProgramObj.userName = MINI_PROGRAM_USER_NAME
        //小程序页面路径；对于小游戏，可以只传入 query 部分，来实现传参效果，如：传入 "?foo=bar"
        miniProgramObj.path = path
        val msg = WXMediaMessage(miniProgramObj)
        // 小程序消息title
        msg.title = title
        // 小程序消息desc
        msg.description = title
        Logger.e("thumb===>${thumb.size}")
        // 小程序消息封面图片，小于128k
        msg.thumbData = thumb
        val req = SendMessageToWX.Req()
        req.transaction = buildTransaction("miniProgram")
        req.message = msg
        // 目前只支持会话
        req.scene = SendMessageToWX.Req.WXSceneSession
        api.sendReq(req)
    }

    private fun buildTransaction(type: String): String {
        return type + System.currentTimeMillis()
    }

    /**
     * 商品分享好友
     */
    fun goodsShareWx(
        loa: ILifecycleOwnerActivity, vb: ViewGoodsShareWxBinding,
        url: String, name: String, priceDesc: String, marketPrice: String, goodsId: Int,
    ) {
        loa.mLoaLifecycleOwner?.launchUI({
            suspendLoadImage(loa.mLoaContext, url, vb.ivShareWxImage)
            vb.tvShareWxName.text = name
            val money = priceDesc + "起"
            vb.tvShareWxMoney.textSpan(money) {
                spanText = "￥"
                addAbsoluteSizeSpan(15.dp)
                spanText = "起"
                addAbsoluteSizeSpan(12.dp)
                addForegroundColorSpan(R.color.text_hint_color_2.toColor())
            }
            vb.tvShareWxSubMoney.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            vb.tvShareWxSubMoney.text = marketPrice
            vb.buttonQ.setTextColor(R.color.text_color.toColor())
            val bitmap = suspendCancellableCoroutine<Bitmap> { coroutine ->
                vb.llShareWx.post {
                    vb.llShareWx.isDrawingCacheEnabled = true
                    vb.llShareWx.buildDrawingCache()
                    coroutine.resume(vb.llShareWx.drawingCache)
                }
            }
            suspendShareMiniProgram(
                loa.mLoaContext,
                "pages/good/good?id=${goodsId}&phone=${UserCache.getUserInfoBean().phone}",
                "你的好友给你推荐了一个商品，快来看看吧",
                bitmap
            )
        }, ApiObserver(loa.mLoaContext))
    }

    /**
     * 商品分享朋友圈
     */
    fun goodsShareWxCircle(
        loa: ILifecycleOwnerActivity, activity: BaseActivity<*>, vb: ViewGoodsShareWeixinCircleBinding, saveImage: Boolean,
        url: String, name: String, priceDesc: String, goodsId: Int,
    ) {
        loa.mLoaLifecycleOwner?.launchUI({
            suspendLoadImage(loa.mLoaContext, url, vb.ivShareImage)
            suspendLoadImage(loa.mLoaContext, mallApi.shareCode(goodsId).toData()?.url ?: "", vb.ivShareQrcode)
            vb.ivShareGoodsName.text = name
            val money = priceDesc + "起"
            vb.ivShareGoodsPrice.textSpan(money) {
                spanText = "￥"
                addAbsoluteSizeSpan(15.dp)
                spanText = "起"
                addAbsoluteSizeSpan(12.dp)
                addForegroundColorSpan(R.color.text_hint_color_2.toColor())
            }
            vb.llShareRoot.post {
                vb.llShareRoot.isDrawingCacheEnabled = true
                vb.llShareRoot.buildDrawingCache()
                if (saveImage) {
                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.Q && !Environment.isExternalStorageLegacy()) {
                        AlbumUtils.saveBitmap(activity, vb.llShareRoot.drawingCache, "${System.currentTimeMillis()}.png")
                        "保存成功".toastMessageLong()
                    } else {
                        activity.permissionRequest {
                            permission(Permission.WRITE_EXTERNAL_STORAGE)
                            onGranted {
                                AlbumUtils.saveBitmap(activity, vb.llShareRoot.drawingCache, "${System.currentTimeMillis()}.png")
                                "保存成功".toastMessageLong()
                            }
                        }
                    }
                } else {
                    ShareAction(activity)
                        .setPlatform(SHARE_MEDIA.WEIXIN_CIRCLE)
                        .withMedia(UMImage(loa.mLoaContext, vb.llShareRoot.drawingCache))
                        .share()
                }
            }
        }, ApiObserver(loa.mLoaContext))
    }

    /**
     * 订单赠送
     */
    fun orderTransfer(
        loa: ILifecycleOwnerActivity, vb: ViewOrderTransferBinding,
        url: String, name: String, priceDesc: String, marketPrice: String, orderSn: String,
    ) {
        loa.mLoaLifecycleOwner?.launchUI({
            val leaveMessage = alertTransferLeaveMessage((loa.mLoaContext as? BaseActivity<*>))
            MALL_API_SERVICE.transfer(leaveMessage, orderSn).toData()
            suspendLoadImage(loa.mLoaContext, url, vb.ivShareWxImage)
            vb.tvShareWxName.text = name
            vb.tvShareWxMoney.textSpan(priceDesc) {
                spanText = "￥"
                addAbsoluteSizeSpan(15.dp)
            }
            vb.tvShareWxSubMoney.paint.flags = Paint.STRIKE_THRU_TEXT_FLAG
            vb.tvShareWxSubMoney.text = marketPrice
            vb.buttonQ.setTextColor(R.color.text_color.toColor())
            val bitmap = suspendCancellableCoroutine<Bitmap> { coroutine ->
                vb.llShareWx.post {
                    vb.llShareWx.isDrawingCacheEnabled = true
                    vb.llShareWx.buildDrawingCache()
                    coroutine.resume(vb.llShareWx.drawingCache)
                }
            }
            suspendShareMiniProgram(
                loa.mLoaContext, "pages/index/index?sn=${orderSn}&phone=${UserCache.getUserInfoBean().phone}",
                "你收到来自${handleLoginName(UserCache.getUserInfoBean().phone)}的一个礼品赠送，快来收下吧",
                bitmap
            )
        }, ApiObserver(loa.mLoaContext))
    }

    /**
     * 订单赠送
     */
    /*suspend fun orderTransfer(context: Context, orderSn: String, picUrl: String) {
        val leaveMessage = alertTransferLeaveMessage((context as? BaseActivity<*>))
        MALL_API_SERVICE.transfer(leaveMessage, orderSn).toData()
        suspendShareMiniProgram(
            context, "pages/index/index?sn=${orderSn}&phone=${UserCache.getUserInfoBean().phone}",
            "你收到来自${handleLoginName(UserCache.getUserInfoBean().phone)}的一个礼品赠送，快来收下吧",
            picUrl
        )
    }*/

    suspend fun alertTransferLeaveMessage(activity: BaseActivity<*>?) = suspendCancellableCoroutine<String> { coroutine ->
        if (activity != null) {
            activity.showAlertInputDialog {
                mCancelable = false
                message(message = "转赠可以给用户留言哦，确认转赠吗?")
                hint("请输入留言...(选填)")
                negativeButton {
                    coroutine.resumeWithException(FirmException("取消转赠"))
                }
                positiveButton {
                    coroutine.resume(it)
                }
            }
        } else {
            coroutine.resume("")
        }
    }

    suspend fun suspendLoadImage(context: Context?, url: String, imageView: ImageView) {
        if (context != null) {
            val bitmap: Bitmap? = withContext(Dispatchers.IO) {
                Logger.e("suspendLoadImageurl==>$url")
                Glide.with(context)
                    .asBitmap()
                    .load(url)
                    .submit()
                    .get()
            }
            if (bitmap != null) {
                imageView.setImageBitmap(bitmap)
            }
        }
    }
}